/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* dummy = new ListNode(0, head);
        ListNode* groupPre = dummy;
        while (true) {
            ListNode* cur = groupPre;
            int kth = k;
            while (kth > 0 && cur) {
                kth--;
                cur = cur->next;
            }
            if (!cur) {
                break;
            }
            ListNode* groupNxt = cur->next;
            ListNode* pre = groupNxt;
            cur = groupPre->next;
            ListNode* tmp = NULL;
            while (cur != groupNxt) {
                tmp = cur->next;
                cur->next = pre;
                pre = cur;
                cur = tmp;
            }
            tmp = groupPre->next;
            groupPre->next = pre;
            groupPre = tmp;
        }
        return dummy->next;
    }
};
